/**
 * 文章数据模型
 * 
 */
module.exports = class Article extends require('./model'){
    /**
     * 获取热门推荐文章
     * @param {int} num 条目数
     */
    static getHot(num){
        return new Promise((resolve,reject) =>{
            let sql = 'SELECT id,title,content,`time`,thumbnail FROM article WHERE hot = 1 LIMIT ?'
            // 父类继承的方法query
            this.query(sql,num).then(res =>{
                resolve(res);
            }).catch(err =>{
                console.log(`获取热门推荐文章失败:${err.message}`);
                reject(err);
            });
        });
    }
    /**
     * 获取最新文章列表
     */
    static getList(){
        let sql = 'SELECT id,title,content,`time`,thumbnail FROM article ORDER BY TIME DESC';
        return this.getPromise(sql,'获取文章列表失败');
    }
    /**
     * 获取指定目录下的文章列表
     * @param {int} id 类目编号
     */
    static getListCategoryId(id){
        let sql = 'SELECT id,title,content,`time`,thumbnail FROM article WHERE category_id = ? ORDER BY TIME DESC';
        return this.getPromise(sql,'获取指定目录下的文章列表失败',id);
    }
    /**
     * 获取指定关键词的文章列表
     * @param {int} id 类目编号
     */
    static getListBykeywrod(keyword){
        let sql = "SELECT id,title,content,`time`,thumbnail FROM article WHERE title LIKE ? ORDER BY TIME DESC";
        return this.getPromise(sql,'获取指定关键词的文章列表失败',`%${keyword}%`);
    }
    /**
     * 获取指定文章的详情
     * @param {int} id 文章编号
     */
    static getArticleById(id){
        return new Promise((resolve,reject) =>{
            let sql = "SELECT a.id,a.title,a.content,a.`time`,a.hits,a.category_id,c.name FROM article a,category c WHERE a.id= ? AND a.`category_id` = c.id";
            // 父类继承的方法query
            this.query(sql,id).then(res =>{
                resolve(res[0]);
            }).catch(err =>{
                console.log(`获取指定文章的详情失败:${err.message}`);
                reject(err);
            });
        });
    }

    /**
     * 获取上一篇文章
     * @param {int} id 当前的文章编号
    */
    static getPrevArticle(id){
        return new Promise((resolve,reject) =>{
            let sql = "SELECT id,title FROM `article` WHERE id < ? ORDER BY id DESC LIMIT 1";
            // 父类继承的方法query
            this.query(sql,id).then(res =>{
                resolve(res[0]);
            }).catch(err =>{
                console.log(`获取上一篇文章失败:${err.message}`);
                reject(err);
            });
        });
    }

    /**
     * 获取下一篇文章
     * @param {int} id 当前的文章编号
    */
    static getNextArticle(id){
        return new Promise((resolve,reject) =>{
            let sql = "SELECT id,title FROM `article` WHERE id > ? ORDER BY id ASC LIMIT 1";
            // 父类继承的方法query
            this.query(sql,id).then(res =>{
                resolve(res[0]);
            }).catch(err =>{
                console.log(`获取下一篇文章失败:${err.message}`);
                reject(err);
            });
        });
    }

}